<?php
/**
 * Created by PhpStorm.
 * User: 盛茂国
 * Tel: 18394333958
 * Date: 2020/6/2
 * Time: 10:31
 */
namespace app\admin\controller;

use app\admin\library\Auth;
use app\admin\model\AuthGroup;
use app\admin\model\Storeinfo;
use app\common\controller\Backend;
use think\Db;
use think\Request;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Store extends Backend
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 布局模板
     * @var string
     */
    protected $layout = 'default';

    /**
     * 权限控制类
     * @var Auth
     */
    protected $auth = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'storeid';

    /**
     * 是否是关联查询
     */
    protected $relationSearch = false;

    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
    protected $dataLimit = false;

    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'admin_id';

    /**
     * 数据限制开启时自动填充限制字段值
     */
    protected $dataLimitFieldAutoFill = true;

    /**
     * 是否开启Validate验证
     */
    protected $modelValidate = true;

    /**
     * 是否开启模型场景验证
     */
    protected $modelSceneValidate = true;

    /**
     * Multi方法可批量修改的字段
     */
    protected $multiFields = 'status';

    /**
     * Selectpage可显示的字段
     */
    protected $selectpageFields = '*';

    /**
     * 前台提交过来,需要排除的字段数据
     */
    protected $excludeFields = "";
    
    /**
     * Store模型对象
     * @var \app\admin\model\Store
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Store;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin2/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $admin_id=$this->auth->id;
        $auth=new Auth();
        $gid=$auth->getGroups($admin_id);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //如果用户是门店主人则查询他本人的门店
            if($gid[0]['name']==='店主角色'){
                $total = $this->model
                    ->with(['storeinfo'])
                    ->with(['admin'])
                    ->where($where)
                    ->where('admin_id','=',$admin_id)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['storeinfo'])
                    ->with(['admin'])
                    ->where($where)
                    ->where('admin_id','=',$admin_id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }else{
                $total = $this->model
                    ->with(['storeinfo'])
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['storeinfo'])
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            foreach ($list as $row) {
                $row->visible(['storeid','storename','storeimages','identimages','address','admin_id']);
                $row->visible(['storeinfo']);
                $row->visible(['admin']);
				$row->getRelation('storeinfo')->visible(['storeinfoid','images','tel','range','storeid']);
				$row->getRelation('admin');//->visible(['id','username']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {

        $uids=db('auth_group_access')->where('group_id',8)->column('uid');
        $uidsstr=implode(',',$uids);
        $alreads=db('store')->column('admin_id');
        $except=implode(',',$alreads);
        $admins=db('admin')->where('id','in',$uidsstr)->where('id','not in',$except)->field(['id','username','nickname'])->select();

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    //print_r($params);die;
                    $result = $this->model->allowField(true)->save($params);
                    $pk=$this->model->storeid;
                    $this->model->relsave($pk,$params['storeinfo']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign('admins',$admins);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $storeinfoid=$row->storeinfo->storeinfoid;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $result = $row->allowField(true)->save($params);

                    $params['storeinfo']['storeinfoid']=$storeinfoid;
                    $row->storeinfo()->update($params['storeinfo']);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }

            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->together('storeinfo')->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function shop(Request $request){
        if($request->isGet()){
            $storeid=$request->param('ids');
            $shops=db('shop')->where('storeid','=',$storeid)->select();

            foreach ($shops as $k=>$shop){
                $shops[$k]['snumber']=db('storeshopnumber')->where(['shopid'=>$shop['shopid'],'storeid'=>$shop['storeid']])->value('number');
            }
            //dump($shops);die;
            foreach ($shops as $list=>$item){
                $shops[$list]['storeid']=$storeid;
                $srcs=$item['shop_image'];
                $srcsarr=explode(',',$srcs);
                $shops[$list]['shop_image']="";
                if(is_array($srcsarr)){
                    foreach ($srcsarr as $vo){
                        $shops[$list]['shop_image'].="<img src=$vo width='40' height='40'>";
                    }
                }else{
                    $shops[$list]['shop_image']=$srcsarr;
                }

            }
            $this->assign('shops',$shops);
        }else{
            $this->error('非法请求');
        }


        return $this->fetch();
    }

}
